package com.example.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.entity.ReportData;
import com.example.entity.vo.ReportDataDTO;
import com.example.entity.vo.ReportDataDTO2;
import com.example.entity.vo.ReportDataDTO3;
import com.example.entity.vo.ReportDataVO;
import com.example.util.ReportDataUtils;
import com.example.util.ReportDataVOUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import java.util.LinkedHashMap;
import java.util.List;

/**
 * @Author ZHAO Yudong
 * @Date 2020/11/17 11:19
 * @description：风控数据
 */
@Slf4j
@Service
public class ReportDataService {

    private List<ReportData> list = ReportDataUtils.getData();
    private RestTemplate restTemplate = new RestTemplate();


    public void crawler1() {
        log.info("-------------------------------------");
        log.info("开始 新农主体报告查询");

        //设置超时时间
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(60 * 1000);
        requestFactory.setReadTimeout(60 * 1000);
        restTemplate.setRequestFactory(requestFactory);

        //restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());


        long startTime = System.currentTimeMillis();//开始时间


        for (int i = 500; i < list.size(); i++) {
            log.info("-- 第 {} 条数据", i);
            String farmName = list.get(i).getFarmName();
            log.info("farmname = {}", farmName);

            ReportDataVO reportDataVO = new ReportDataVO();
            reportDataVO.setFarmName(farmName);
            reportDataVO.setId(i);

            //开始查询
            if (farmName != null) {
                if (farmName.equals("家庭农场") || farmName.equals("家庭农场主") || farmName.equals("农场") || farmName.equals("null") || farmName.equals("")) {
                    ReportDataVOUtils.add2(reportDataVO);
                } else {
                    request1(reportDataVO, farmName);
                }
            } else {
                ReportDataVOUtils.add2(reportDataVO);
            }

            try {
                Thread.currentThread().sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        long endTime = System.currentTimeMillis();//结束时间
        log.info("数据查询查询 耗时:" + (endTime - startTime) / 1000 + "s");

        List<ReportDataVO> data = ReportDataVOUtils.getData();
        data.stream().forEach(System.out::println);
        EasyExcel.write("C:\\Users\\Administrator\\Desktop\\数据导出-03.xlsx", ReportDataVO.class).sheet().doWrite(ReportDataVOUtils.getData());
        EasyExcel.write("C:\\Users\\Administrator\\Desktop\\数据导出-04.xlsx", ReportDataVO.class).sheet().doWrite(ReportDataVOUtils.getData2());
//        EasyExcel.write("C:\\Users\\yudong\\Desktop\\数据导出-01.xlsx", ReportDataVO.class).sheet().doWrite(ReportDataVOUtils.getData());

    }


    /*public void crawler() {
        log.info("-------------------------------------");
        log.info("开始 新农主体报告查询");

        //设置超时时间
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(60 * 1000);
        requestFactory.setReadTimeout(60 * 1000);
        restTemplate.setRequestFactory(requestFactory);

        //restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());

        //ExecutorService threadPool = Executors.newCachedThreadPool();
        ExecutorService threadPool = Executors.newFixedThreadPool(1);
        CountDownLatch latch = new CountDownLatch(100);
        long startTime = System.currentTimeMillis();//开始时间

        for (int i = 0; i < 100; i++) {
            final int index = i;
            Runnable run = () -> {
                try {
                    //处理业务逻辑
                    System.out.println("[1]" + Thread.currentThread().getName() + "----" + index);

                    String farmName = list.get(index).getFarmName();
                    log.info("farmname = {}", farmName);
                    if (farmName != null) {
                        request1(reportDataVO, farmName);
                    }

                } finally {
                    latch.countDown();
                }
            };
            threadPool.execute(run);
        }
        try {
            //等待所有线程执行完毕
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        threadPool.shutdown();//关闭线程池

        long endTime = System.currentTimeMillis();//结束时间
        log.info("数据查询查询 耗时:" + (endTime - startTime) / 1000 + "s");

        List<ReportDataVO> data = ReportDataVOUtils.getData();
        data.stream().forEach(System.out::println);
        EasyExcel.write("C:\\Users\\Administrator\\Desktop\\数据导出.xlsx", ReportDataVO.class).sheet().doWrite(ReportDataVOUtils.getData());

    }*/

    private void request1(ReportDataVO reportDataVO, String farmName) {
        log.info("farmname : {} -- 查询主体信息 ", farmName);
        String uri = "http://47.97.24.115:8283/creditReport/getReportList?farmName={farmName}";
        // headers
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // request
        HttpEntity<Object> request = new HttpEntity<>(headers);
        try {
            ResponseEntity<String> entity = restTemplate.postForEntity(uri, request, String.class, farmName);
            ReportDataDTO data = JSON.parseObject(entity.getBody(), ReportDataDTO.class);
            if (data != null) {
                List<ReportDataDTO.DataDTO.ReportListDTO> reportList = data.getData().getReportList();
                if (reportList != null && reportList.size() == 1) {
                    ReportDataDTO.DataDTO.ReportListDTO dto = data.getData().getReportList().get(0);
                    log.info("farmname : {},主体信息 = {}", farmName, dto);


                    reportDataVO.setFarmid(dto.getFarmid());
                    reportDataVO.setLegalid(dto.getLegalid());
                    reportDataVO.setFarmName(farmName);
                    reportDataVO.setFarmer(dto.getFarmer());
                    reportDataVO.setDistinct(dto.getCity());

                    requestZt(reportDataVO, dto.getFarmid(), dto.getLegalid());
                } else if (reportList != null && reportList.size() == 1) {
                    log.info("{} 查询list size > 1", farmName);
                    ReportDataVOUtils.add2(reportDataVO);
                } else {
                    log.info("{} 查询list = null 或 0", farmName);
                    ReportDataVOUtils.add2(reportDataVO);
                }
            } else {
                log.info("{} 查询结果响应 null", farmName);
                ReportDataVOUtils.add2(reportDataVO);
            }


        } catch (HttpClientErrorException e) {
            System.out.println(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
//            throw e;
        }
    }

    private void requestZt(ReportDataVO reportDataVO, Integer farmid, Integer legalid) {
        log.info("farmname : {} -- 查询农场信息", reportDataVO.getFarmName());

        String uri = "http://47.97.24.115:8283/creditReport/getFarmInfo?farmid={farmid}";
        log.info("farmname : {},farmid = {}", reportDataVO.getFarmName(), farmid);

        // headers
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        // param
        LinkedHashMap<String, Integer> map = new LinkedHashMap();
        map.put("farmid", farmid);

        // request
        HttpEntity<Object> request = new HttpEntity<>(headers);
        try {
            ResponseEntity<String> entity = restTemplate.postForEntity(uri, request, String.class, map);
            //JSONObject data = JSON.parseObject(entity.getBody());
            ReportDataDTO2 dto2 = JSON.parseObject(entity.getBody(), ReportDataDTO2.class);
            log.info("farmname : {},农场信息 = {}", reportDataVO.getFarmName(), dto2);
            if (dto2 != null) {
                ReportDataDTO2.DataDTO data = dto2.getData();
                if (data != null) {
                    reportDataVO.setDistinct(data.getDistrict());
                    reportDataVO.setZt(getZT(data.getFarmType()));
                    reportDataVO.setLevel(getLevel(data.getFarmLevel()));
                    reportDataVO.setYw(data.getIndustryType());
                } else {
                    log.info("farmname : {} -- 查询农场信息 data为空", reportDataVO.getFarmName());
                }

            } else {
                log.info("farmname : {} -- 查询农场信息 响应为空", reportDataVO.getFarmName());
            }
            requestZs(reportDataVO, legalid);

        } catch (HttpClientErrorException e) {
            System.out.println(e.getMessage());
        }

    }

    private void requestZs(ReportDataVO reportDataVO, Integer legalid) {
        log.info("farmname : {} -- 查询得分信息", reportDataVO.getFarmName());

        String uri = "http://47.97.24.115:8283/creditExamine/examineReportByIdNum?legalid={legalid}";
        log.info("farmname : {},legalid = {}", reportDataVO.getFarmName(), legalid);


        // param
        JSONObject json = new JSONObject();
        json.put("legalid", legalid);

        try {
            ResponseEntity<String> entity = restTemplate.getForEntity(uri, String.class, json);
            //JSONObject data = JSON.parseObject(entity.getBody());
            ReportDataDTO3 dto3 = JSON.parseObject(entity.getBody(), ReportDataDTO3.class);
            log.info("farmname : {},得分信息 = {}", reportDataVO.getFarmName(), dto3);
            if (dto3 != null) {
                ReportDataDTO3.DataDTO data = dto3.getData();

                reportDataVO.setJbInfo(data.get基本信息报告得分());
                reportDataVO.setJyInfo(data.get农业行为报告得分());//经营信息
                reportDataVO.setDkInfo(data.get农业贷款报告得分());
                reportDataVO.setBxInfo(data.get农业保险报告得分());
                reportDataVO.setZcInfo(data.get农业补贴报告得分());//政策信息
                reportDataVO.setGgInfo(data.get公共信息得分());
                reportDataVO.setTotal(data.getScore());
                reportDataVO.setFenwei(data.getRank());
            }
            ReportDataVOUtils.add(reportDataVO);

        } catch (HttpClientErrorException e) {
            System.out.println(e.getMessage());
        } catch (Exception e) {
            ReportDataVOUtils.add2(reportDataVO);
            e.printStackTrace();
//            throw e;
        }
    }

    private String getZT(Integer i) {
        String content = null;
        if (i != null) {
            switch (i) {
                case -1:
                    break;
                case 0:
                    content = "家庭农场";
                    break;
                case 1:
                    content = "合作社";
                    break;
                case 2:
                    content = "普通农户";
                    break;
                case 3:
                    content = "农业企业";
                    break;
                case 4:
                    content = "种养大户";
                    break;
                case 5:
                    content = "名宿";
                    break;
                case 6:
                    content = "股份经济合作社";
                    break;
                default:
                    content = i.toString();
                    break;

            }
        }
        return content;
    }

    private String getLevel(Integer i) {
        String content = null;
        if (i != null) {
            switch (i) {
                case 0:
                    content = "普通";
                    break;
                case 1:
                    content = "县级";
                    break;
                case 2:
                    content = "市级";
                    break;
                case 3:
                    content = "省级";
                    break;
                case 4:
                    content = "国家";
                    break;
                default:
                    content = i.toString();
                    break;
            }
        }
        return content;
    }
}
